import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zyj
 * @date 2022年06月09日 11:06
 * ReentrantLock
 */
public class 线程通信方式四 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
       Condition condition =  lock.newCondition();
        List<String> list = new ArrayList<>();
        new Thread(() -> {
            lock.lock();
            while (true) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程B执行任务......");
                break;
            }
            lock.unlock();
        }).start();
        new Thread(() -> {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                list.add("abc");
                System.out.println("线程A向list中添加一个元素，此时list中的元素个数为：" + list.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (list.size() == 5){
                    condition.signal();
                }
            }
            lock.unlock();
        }).start();
    }
}
